import {
  createStoreBindings
} from 'mobx-miniprogram-bindings'
import {
  store
} from '../../store/store'
const QRCode = require('../../utils/weapp-qrcode.js')
let qrcode

const W = wx.getSystemInfoSync().windowWidth
const rate = 750.0 / W
const code_w = 280 / rate

Page({
  data: {
    name: '',
    type: 'ERC',
    code_w: code_w,
    path: '',
    address: ''
  },
  onLoad: function (options) {
    this.storeBindings = createStoreBindings(this, {
      store,
      fields: ['FIL', 'USDT'],
    })
    if (options.title) {
      this.setData({
        name: options.title
      })
    }
  },
  onReady() {
    if (this.data.name) {
      let wallet
      if (this.data.name == 'FIL') {
        wallet = this.data.FIL
      } else if (this.data.name == 'USDT') {
        wallet = this.data.USDT
      }
      this.setData({
        address: wallet.address
      })
    }
    qrcode = new QRCode('canvas', {
      text: this.data.address,
      width: code_w,
      height: code_w,
      colorDark: "#000000",
      colorLight: "#ffffff",
      correctLevel: QRCode.CorrectLevel.H,
    })
    qrcode.exportImage(params => {
      this.setData({
        path: params.path
      });
    })
  },
  onUnload() {
    this.storeBindings.destroyStoreBindings()
  },
  /**
   * 点击切换链名称
   */
  switchChain(e) {
    if (this.data.type == e.currentTarget.dataset.chain) return
    this.setData({
      type: e.currentTarget.dataset.chain
    })
    if (this.data.type == 'ERC') {
      const wallet = this.data.USDT
      this.setData({
        address: wallet.address
      })
    } else if (this.data.type == 'TRC') {
      this.setData({
        address: this.data.address + 'TXY'
      })
    }
    this.setData({
      path: null
    })
    this.makeCode()
  },
  /**
   * 重新生成二维码
   */
  makeCode() {
    qrcode.makeCode(this.data.address)
    qrcode.exportImage(params => {
      this.setData({
        path: params.path
      });
    })
  },
  /**
   * 长按保存
   */
  save() {
    wx.showActionSheet({
      itemList: ['保存图片'],
      success: (res) => {
        if (res.tapIndex == 0) {
          wx.saveImageToPhotosAlbum({
            filePath: this.data.path,
            success: () => {
              wx.showToast({
                title: '保存成功',
                icon: 'success',
                duration: 2000
              })
            }
          })
        }
      }
    })
  },
  /**
   * 点击复制
   */
  copy() {
    wx.setClipboardData({
      data: this.data.address
    })
  },
  /**
   * 去历史记录
   */
  abc() {
    console.log(1)
  }
})